package edu.ucsc.gameAI.conditions;

import java.util.Vector;

import pacman.game.Constants.GHOST;
import pacman.game.Game;
import edu.ucsc.gameAI.ICondition;
import edu.ucsc.gameAI.PacmanConstants;

public class NoSafePathToAnyEdibleGhosts implements ICondition {

	@Override
	public boolean test(Game game) {
		
		Vector<GHOST> edibleGhosts = new Vector<GHOST>();
		Vector<GHOST> nonEdibleGhosts = new Vector<GHOST>();
		
		int pacManCurrentNode = game.getPacmanCurrentNodeIndex();
		
		for (GHOST ghost: GHOST.values()){
			if(game.isGhostEdible(ghost)){ //If any Ghosts Are Edible
				edibleGhosts.add(ghost); // store which ghosts are edible.	
			}
			else{
				nonEdibleGhosts.add(ghost);
			}
		}
		
		boolean safeGhostFound = true;
		boolean noSafePathFound = true;
		int currentEdibleGhostIndex = -1;
		
		for (GHOST edibleGhost: edibleGhosts)
		{		
			safeGhostFound = true;
			currentEdibleGhostIndex = game.getGhostCurrentNodeIndex(edibleGhost);
			
			//Ok, sweet! We've got the closest edible ghost!
			//BUT... are there any non-edible ghosts in between him and I?
			//If so.. then.. umm.. let's leave it well enough alone!
			int[] pathToCurrentEdibleGhost = game.getShortestPath(pacManCurrentNode, currentEdibleGhostIndex);

			for(GHOST dangerGhost : nonEdibleGhosts){
				int currentDangerGhostIndex = game.getGhostCurrentNodeIndex(dangerGhost);
				
				for(int i=0; i < pathToCurrentEdibleGhost.length; i++){
					if(pathToCurrentEdibleGhost[i] ==  currentDangerGhostIndex &&
						game.getShortestPathDistance(pacManCurrentNode, currentDangerGhostIndex) < PacmanConstants.safeDistance)
					{
						//uh oh; the current path we want to walk on contains a ghost. That means that this path isn't any good.
						safeGhostFound = false;
						break;
					}
				}
				if(!safeGhostFound){
					break; // let's look at the next edible ghost -- maybe it will be safer to chase.
				}
			}
			if(safeGhostFound)
			{
				int currentEdibleGhostDistance = game.getShortestPathDistance(pacManCurrentNode, currentEdibleGhostIndex);

				switch(game.getActivePowerPillsIndices().length)
				{
				case 4:
					noSafePathFound = false;
					break;
				case 3: 
					if (currentEdibleGhostDistance < 
							PacmanConstants.edibleGhostDistance - PacmanConstants.threePPRemainDistanceToCheck)
						noSafePathFound = false;
					break;
				case 2: 
					if (currentEdibleGhostDistance < 
							PacmanConstants.edibleGhostDistance - PacmanConstants.twoPPRemainDistanceToCheck)
						noSafePathFound = false;
					break;
				case 1: 
					if (currentEdibleGhostDistance < 
							PacmanConstants.edibleGhostDistance - PacmanConstants.onePPRemainsDistanceToCheck)
						noSafePathFound = false;
					break;
				case 0: 
					if (currentEdibleGhostDistance < 
							PacmanConstants.edibleGhostDistance - PacmanConstants.noPPRemainDistanceToCheck)
						noSafePathFound = false;
					break;
				}
			}
		}
		return noSafePathFound;
	}
}
